package com.ruoyi.lvlian.util;

import net.sourceforge.pinyin4j.PinyinHelper;
import net.sourceforge.pinyin4j.format.HanyuPinyinCaseType;
import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;
import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;
import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.concurrent.atomic.AtomicInteger;

public class ContactNumGenerator {
    private static final AtomicInteger counter = new AtomicInteger(1);
    private static final int REGION_MAX_LENGTH = 4; // 地域名称最大长度限制

    public static String generateSerialNumber(String region, String name) {
        // 1. 处理地域名称（超过4字则截取前4字）
        String processedRegion = region.length() > REGION_MAX_LENGTH ?
                region.substring(0, REGION_MAX_LENGTH) : region;
        String regionAbbr = getPinyinAbbreviation(processedRegion, true);

        // 2. 生成姓名拼音缩写（大写）
        String nameAbbr = getPinyinAbbreviation(name, false);

        // 3. 获取当前日期
        String date = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyyMMdd"));

        // 4. 生成序号
        String sequence = String.format("%03d", counter.getAndIncrement());

        return String.format("%s-%s-%s-%s", regionAbbr, nameAbbr, date, sequence);
    }

    private static String getPinyinAbbreviation(String input, boolean isRegion) {
        if (input == null || input.trim().isEmpty()) {
            return "";
        }

        StringBuilder abbr = new StringBuilder();
        HanyuPinyinOutputFormat format = new HanyuPinyinOutputFormat();
        format.setCaseType(HanyuPinyinCaseType.UPPERCASE);
        format.setToneType(HanyuPinyinToneType.WITHOUT_TONE);

        try {
            int maxLength = isRegion ? input.length() : Math.min(input.length(), 2);
            for (int i = 0; i < maxLength; i++) {
                char c = input.charAt(i);
                if (isChinese(c)) {
                    String[] pinyinArray = PinyinHelper.toHanyuPinyinStringArray(c, format);
                    if (pinyinArray != null && pinyinArray.length > 0) {
                        abbr.append(pinyinArray[0].charAt(0));
                    }
                } else {
                    abbr.append(Character.toUpperCase(c));
                }
            }
        } catch (BadHanyuPinyinOutputFormatCombination e) {
            throw new RuntimeException("拼音转换失败", e);
        }
        return abbr.toString();
    }

    private static boolean isChinese(char c) {
        return (c >= 0x4E00 && c <= 0x9FA5);
    }

    public static void main(String[] args) {
        System.out.println(generateSerialNumber("山东太通公司的", "朱迪")); // 输出：SDTT-ZD-20250617-001
        System.out.println(generateSerialNumber("北京科技有限公司", "张三")); // 输出：BJKJ-ZS-20250617-002
    }
}